<script lang="ts" setup>
import { reactive, ref, onMounted } from "vue";
import type { FormInstance, FormRules } from "element-plus";
import {
  getServiceList,
  createWarehousing,
  modifyWarehousing
} from "/@/api/warehousing";
import { ElMessage } from "element-plus";
import { getServiceOptionList } from "/@/api/service";
import { isUserRole } from "/@/utils/index";

type Props = {
  modelValue: boolean;
  isAdmin: boolean;
  userList: any;
  formData: any;
  title: string;
};
const props = withDefaults(defineProps<Props>(), {
  modelValue: false,
  isAdmin: false,
  userList: () => [],
  formData: () => ({}),
  title: ""
});
const emit = defineEmits(["update:modelValue", "submit-success"]);
const inputHandle = val => {
  emit("update:modelValue", val);
};

// onMounted(() => {
//   setTimeout(() => {
//     getServiceData();
//   }, 1000);
// });

const inputWidth = "190px";

const ruleFormRef = ref<FormInstance>();
const rules = reactive<FormRules>({
  type: [{ required: true, message: "请选择", trigger: "change" }],
  service_id: [{ required: true, message: "请选择", trigger: "change" }],
  checkout_name: [{ required: true, message: "请填写", trigger: "blur" }]
});
const innerVisible = ref(false);
const serviceForm = reactive({
  userNid: "",
  id: "",
  subId: "",
  price: "",
  value: ""
});

const selectData = reactive({
  // 表单类型list
  typeList: [
    { label: "提柜", value: 1 },
    { label: "中转", value: 2 },
    { label: "退件", value: 3 }
  ],
  serviceIdList: []
});

const serviceOption = reactive({
  label: "",
  list: []
});
const showServiceOption = ref(false);

const getServiceData = () => {
  getServiceList({ user_nid: serviceForm.userNid }).then(({ data }) => {
    selectData.serviceIdList = data;
  });
};

// 表单提交事件
const submitForm = async (formEl: FormInstance | undefined) => {
  if (props.formData.container_no === "") {
    return ElMessage({
      type: "warning",
      message: "请输入柜号"
    });
  }
  if (props.formData.container_no.length !== 11) {
    return ElMessage({
      type: "warning",
      message: "柜号固定位数11位"
    });
  }
  if (!formEl) return;
  await formEl.validate(valid => {
    if (valid) {
      let request;
      let fn;
      if (props.title === "创建入库清单") {
        fn = createWarehousing;
        const {
          user_name,
          user_nid,
          type,
          container_no,
          bill_of_lading,
          shipping_company,
          estimated_time,
          notes,
          service
        } = props.formData;
        request = {
          user_name,
          user_nid,
          type,
          container_no,
          bill_of_lading,
          shipping_company,
          estimated_time,
          notes,
          service
        };
      } else {
        fn = modifyWarehousing;
        const {
          identifier,
          user_name,
          user_nid,
          type,
          container_no,
          bill_of_lading,
          shipping_company,
          estimated_time,
          notes,
          service
        } = props.formData;
        request = {
          identifier,
          user_name,
          user_nid,
          type,
          container_no,
          bill_of_lading,
          shipping_company,
          estimated_time,
          notes,
          service
        };
      }
      fn(request).then(() => {
        ElMessage({
          type: "success",
          message: props.title === "创建入库清单" ? "创建成功" : "修改成功"
        });
        resetForm(formEl);
        emit("submit-success");
      });
    }
  });
};

// 表单重置事件
const resetForm = (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  formEl.resetFields();
  inputHandle(false);
};

const getUserName = val => {
  props.formData.user_name = props.userList.find(item => item.nid === val).name;
};

const addService = () => {
  innerVisible.value = true;
};

const changeService = val => {
  serviceForm.subId = "";
  const obj = selectData.serviceIdList.find(item => item.id === val);
  serviceForm.price = obj.price;
  if (obj.is_multiple_options === "1") {
    showServiceOption.value = true;
    getServiceOptionList({ service_id: obj.id }).then(({ data }) => {
      serviceOption.label = data.name;
      serviceOption.list = data.info;
    });
  } else {
    showServiceOption.value = false;
  }
};

const submitService = () => {
  const obj = selectData.serviceIdList.find(item => item.id === serviceForm.id);
  const item = {
    service_id: obj.id,
    service_name: obj.name,
    service_option_name: "",
    service_option_value: "",
    service_price: obj.price
  };
  if (serviceForm.subId) {
    const serviceObj = serviceOption.list.find(
      item => item.id === serviceForm.subId
    );
    item.service_option_name = serviceOption.label;
    item.service_option_value = serviceObj.value;
    item.service_price = serviceObj.price;
  }
  props.formData.service.push(item);
  clearHandle();
};

const clearHandle = () => {
  serviceForm.id = "";
  serviceForm.subId = "";
  serviceForm.price = "";
  serviceOption.label = "";
  serviceOption.list = [];
  innerVisible.value = false;
};

const deleteService = i => {
  props.formData.service.splice(i, 1);
};

const changeSubService = val => {
  const obj = serviceOption.list.find(item => item.id === val);
  serviceForm.price = obj.price;
};

const changeUserNid = () => {
  getServiceData();
  (serviceForm.id = ""),
    (serviceForm.subId = ""),
    (serviceForm.price = ""),
    (serviceForm.value = "");
};

defineExpose({
  serviceForm
});
</script>

<template>
  <el-dialog
    :modelValue="modelValue"
    @update:modelValue="inputHandle"
    :title="title"
    width="55%"
  >
    <span>
      <el-form
        :inline="true"
        :model="formData"
        :rules="rules"
        ref="ruleFormRef"
        label-width="auto"
        label-position="left"
      >
        <template v-if="isAdmin">
          <el-form-item label="客户名称:">
            <el-select
              v-model="formData.user_nid"
              :style="{ width: inputWidth }"
              placeholder="请选择"
              @change="getUserName"
            >
              <el-option
                v-for="item in userList"
                :key="item.nid"
                :label="item.name"
                :value="item.nid"
              />
            </el-select>
          </el-form-item>
        </template>
        <el-form-item label="类型:" prop="type">
          <el-select
            v-model="formData.type"
            placeholder="请选择"
            :style="{ width: inputWidth }"
          >
            <el-option
              v-for="item in selectData.typeList"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="柜号:">
          <el-input
            v-model="formData.container_no"
            :style="{ width: inputWidth }"
          />
        </el-form-item>
        <el-form-item label="预计到柜时间:">
          <el-date-picker
            :style="{ width: inputWidth }"
            v-model="formData.estimated_time"
            type="date"
            format="YYYY-MM-DD"
            value-format="YYYY-MM-DD"
          />
        </el-form-item>
        <el-form-item label="船司:">
          <el-input
            v-model="formData.shipping_company"
            :style="{ width: inputWidth }"
          />
        </el-form-item>
        <el-form-item label="提单号:">
          <el-input
            v-model="formData.bill_of_lading"
            :style="{ width: inputWidth }"
          />
        </el-form-item>
        <el-form-item label="备注:">
          <el-input v-model="formData.notes" :style="{ width: inputWidth }" />
        </el-form-item>
        <el-form-item label-width="0px">
          <el-button type="primary" size="small" @click="addService"
            >添加服务</el-button
          >
        </el-form-item>
      </el-form>

      <el-scrollbar
        v-if="formData.service.length"
        max-height="100px"
        :wrap-style="{
          padding: '10px',
          border: '1px solid rgb(227, 227, 227)',
          borderRadius: '5px'
        }"
      >
        <div
          class="service-box-item"
          v-for="(item, i) in formData.service"
          :key="item.service_id"
        >
          <div>{{ item.service_name }}</div>
          <div v-if="item.service_option_value">
            {{ item.service_option_value }}
          </div>
          <div>${{ item.service_price }}</div>
          <div class="delete" @click="deleteService(i)">删除</div>
        </div>
      </el-scrollbar>

      <el-dialog
        v-model="innerVisible"
        width="30%"
        title="添加服务"
        append-to-body
      >
        <span>
          <el-form :model="serviceForm" label-width="auto">
            <el-form-item
              label="客户:"
              v-auth="['admin', 'super', 'warehouse']"
            >
              <el-select
                v-model="serviceForm.userNid"
                placeholder="请选择"
                style="width: 50%"
                @change="changeUserNid"
              >
                <el-option
                  v-for="item in userList"
                  :key="item.nid"
                  :label="item.name"
                  :value="item.nid"
                />
              </el-select>
            </el-form-item>
            <el-form-item label="服务:">
              <el-select
                v-model="serviceForm.id"
                @change="changeService"
                style="width: 50%"
              >
                <el-option
                  v-for="item in selectData.serviceIdList"
                  :key="item.id"
                  :label="item.name"
                  :value="item.id"
                />
              </el-select>
            </el-form-item>
            <el-form-item label="价格:" v-if="serviceForm.price">
              <el-input
                v-model="serviceForm.price"
                style="width: 50%"
                :disabled="isUserRole()"
              />
            </el-form-item>
            <el-form-item
              v-if="showServiceOption && serviceOption.list.length"
              :label="serviceOption.label + ':'"
            >
              <el-select
                v-model="serviceForm.subId"
                style="width: 50%"
                @change="changeSubService"
              >
                <el-option
                  v-for="(item, i) in serviceOption.list"
                  :key="i"
                  :label="item.value"
                  :value="item.id"
                />
              </el-select>
            </el-form-item>
          </el-form>
        </span>
        <template #footer>
          <span class="dialog-footer">
            <el-button @click="clearHandle">取 消</el-button>
            <el-button type="primary" @click="submitService">确 定</el-button>
          </span>
        </template>
      </el-dialog>
    </span>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="resetForm(ruleFormRef)">取 消</el-button>
        <el-button type="primary" @click="submitForm(ruleFormRef)"
          >确 定</el-button
        >
      </span>
    </template>
  </el-dialog>
</template>

<style lang="scss" scoped>
.service-box-item {
  display: flex;

  div {
    margin-right: 40px;
    font-size: 16px;
  }

  .delete {
    color: #409eff;
    cursor: pointer;
  }
}
</style>
